package org.ht.combotable;

import java.util.Vector;

import javax.swing.JTable;
import javax.swing.table.TableColumnModel;

import org.dom4j.Element;
import org.ht.config.ColumnInfoXmlReader;
import org.ht.entity.Column;

public class ComboTableFactory {
	static ColumnGroup[] row1;
	// 保存所有可以显示在界面上的节点信息
	static Vector<Column> vcolumn;
	// 不能在界面上显示的非叶子节点列表
	static Vector<Column> unShowableMixNode;

	public Vector<Column> getVcolumn() {
		return vcolumn;
	}

	static Element root;
	public static ComboTableFactory instance = new ComboTableFactory();

	private ComboTableFactory() {
		root = ColumnInfoXmlReader.getXmlReader().getRootElement();

		vcolumn = ColumnInfoXmlReader.getXmlReader().getNodeInEandC();

		unShowableMixNode = ColumnInfoXmlReader.getXmlReader()
				.getNoShowMixedElements();
	}

	private void getColumnGroup(Element el, ColumnGroup cg) {
		Column tmpCol = new Column();
		tmpCol.cName = (String) el.attributeValue("text");
		tmpCol.eName = (String) el.attributeValue("id");

		// 判断是否复合节点
		if (el.hasMixedContent()) {
			if (unShowableMixNode.contains(tmpCol) == true) {
				return;
			}

			ColumnGroup acg = new ColumnGroup(el.attributeValue("text"));
			cg.add(acg);
			for (Object els : el.elements()) {
				getColumnGroup((Element) els, acg);
			}
		} else {
			// 判断该节点是否是不可显示的，如果确实是不可显示的，就直接返回
			if (vcolumn.contains(tmpCol) == false) {
				return;
			}

			cg.add(cm.getColumn(index));
			index++;
		}
	}

	static TableColumnModel cm;
	static int index;

	/**
	 * 默认查询方法
	 * 
	 * @return
	 */
	public ComboTable getDefaultQuery() {
		ComboTableModel dm = new ComboTableModel();

		dm.setColumnIdentifiers(vcolumn);
		ComboTable table = new ComboTable(dm);
		table.helper.setVcolumn(vcolumn);
		cm = table.getColumnModel();
		index = 0;
		ColumnGroup cg = new ColumnGroup("root");
		getColumnGroup(root, cg);

		MyTableHeader header = (MyTableHeader) table.getTableHeader();

		Vector<Object> vector = ((ColumnGroup) (cg.getVector().get(0)))
				.getVector();
		for (Object obj : vector) {
			header.addColumnGroup((ColumnGroup) obj);
		}

		// TODO 捕捉界面110350328
		// System.out.println(header.getMouseListeners());
		// header.addMouseListener(renderer);
		// header.addMouseListener(renderer.hiddenJToggleButton);
		TableColumnModel model = table.getColumnModel();
		for (int i = 0; i < model.getColumnCount(); i++) {
			MyHeaderButtonRenderer renderer = new MyHeaderButtonRenderer();
			model.getColumn(i).setHeaderRenderer(renderer);
		}

		// table.getColumn("住院号").setMinWidth(0);
		// //table.getColumn("住院号").setMaxWidth(0);
		table.getTableHeader().setUI(new MyGroupTableHeaderUI());
		// header.setHeaderEditable(false);
		table.getModel();
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		return table;
	}
}
